package com.ruoyi.file.utils;

import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.BucketManager;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;

/**
 * @author 15332
 * 七牛云工具类
 */
@Component
public class QiniuUtils {

  private static final Logger log = LoggerFactory.getLogger(QiniuUtils.class);

  /**
   * AK
   */
  @Value("${qiniu.accessKey}")
  private String accessKey;
  /**
   * SK
   */
  @Value("${qiniu.secretKey}")
  private String secretKey;
  /**
   * 空间名称
   */
  @Value("${qiniu.bucketName}")
  private String bucket;
  /**
   * 外链域名
   */
  @Value("${qiniu.url}")
  private String url;

  /**
   * 文件上传
   *
   * @param file     上传文件
   * @param fileName 文件名
   * @return 文件上传成功地址
   */
  public String upload(MultipartFile file, String fileName) {
    try {
      return upload(file.getInputStream(), fileName);
    } catch (Exception e) {
      log.error("{} 文件上传失败：{}", fileName, e);
      return null;
    }
  }

  /**
   * 文件上传
   *
   * @param inputStream 上传文件流
   * @param fileName    文件名
   * @return 文件上传成功地址
   */
  public String upload(InputStream inputStream, String fileName) {
    Auth auth = Auth.create(accessKey, secretKey);
    String upToken = auth.uploadToken(bucket);
    // 构造一个带指定 Region 对象的配置类
    Configuration cfg = new Configuration(Region.region2());
    UploadManager uploadManager = new UploadManager(cfg);
    try {
      Response response = uploadManager.put(inputStream, fileName, upToken, null, null);
      // 解析上传成功的结果
      DefaultPutRet putRet = response.jsonToObject(DefaultPutRet.class);
      if (null != putRet) {
        return url + putRet.key;
      }
    } catch (Exception e) {
      log.error("{} 文件上传失败：{}", fileName, e);
    }
    return null;
  }


  /**
   * 删除
   *
   * @param fileName 文件名
   * @return true 删除成功，false 删除失败
   */
  public Boolean remove(String fileName) {
    Auth auth = Auth.create(accessKey, secretKey);
    Configuration cfg = new Configuration(Region.region2());
    BucketManager bucketManager = new BucketManager(auth, cfg);
    try {
      bucketManager.delete(bucket, fileName);
      return Boolean.TRUE;
    } catch (QiniuException e) {
      log.error("{} 文件删除失败：{}", fileName, e);
      return Boolean.FALSE;
    }
  }
}
